<template>
  <el-tree ref="treeRef" :data="menuList" show-checkbox node-key="resourceId" :props="defaultProps"
    :default-checked-keys="curcheckedArr" :default-expanded-keys="resourceIdList" :renderContent="renderContent"
    render-after-expand @check="checkChange">
  </el-tree>
</template>

<script lang="ts" setup>
  // import { reqAllMenuTree } from "@/api/business/menu";
  import { watch, ref } from 'vue'
  import { getRsourceTreeApi } from '@/utils/globalFn';
  import { reqResourceRoleRelation } from "@/api/business/role";
  import Item from "@/layout/components/Sidebar/Item.vue";
  import { store } from "@/store";
  import { Tree } from "element-plus/es/components/tree-v2/src/types";
  const defaultProps = {
    children: "children",
    label: "label",
  };
  const props = defineProps({
    resourceIdList: {
      type: [Array],
      default: [],
    },
    tenantLevelId: {
      type: Number,
      default: null
    }
  });

  const treeRef = ref();
  // 当前选中的节点
  const curcheckedArr = ref([]);
  const menuList = ref([]);


  // 清空选中的按钮权限
  const clearNodes = (nodes: any = []) => {
    nodes.forEach((item) => {
      let node = treeRef.value.getNode(item.resourceId);
      collapseAllChildren(node);
      node.collapse();
      if (!(item.children && item.children.length)) {
        item.checked = false;
        item.buttonResourceList.map(v => {
          v.checked = false
          return v
        })
      }
      if (item.children && item.children.length) clearNodes(item.children);
    });
  };

  const readNodes = (nodes: any = [], arr: any = []) => {
    for (let item of nodes) {
      item.label = item.resourceName;
      item.checked = false;
      if (props.resourceIdList.length && item.children.length == 0) {
        item.checked = props.resourceIdList.includes(item.resourceId)
        if (item.checked) curcheckedArr.value.push(item.resourceId)
      }
      if (!(item.children && item.children.length) && item.hasOwnProperty('buttonResourceList')) {
        item.buttonResourceList.map(v => {
          if (item.checked) {
            v.allSelect = false
          }
          v.checked = props.resourceIdList.includes(v.resourceId)
          return v
        })
      }
      if (item.children && item.children.length) readNodes(item.children);
    }
  };
  // 展示和隐藏右边按钮
  const checkNodes = (nodes: any[], isCheck: Boolean) => {
    // console.log('nodes', nodes, isCheck);
    setTimeout(() => {
      nodes.forEach((item) => {
        if (item.children && item.children.length) checkNodes(item.children, isCheck);
        if (item.resourceType === 'menu' && item.hasOwnProperty('buttonResourceList') && item.buttonResourceList.length) {
          item.checked = isCheck;
        };
      });
    })
  };
  // 递归子代及后代展开
  const expandAllChildren = (node: object) => {
    if (node.childNodes && node.childNodes.length > 0) {
      for (let i = 0; i < node.childNodes.length; i++) {
        const childNode = node.childNodes[i];
        if (!childNode.isLeaf && !childNode.expanded) {
          childNode.expand();
        }
        expandAllChildren(childNode); // 递归调用展开子节点的子节点
      }
    }
  };
  // 递归子代及后代关闭
  const collapseAllChildren = (node: object) => {

    if (node.childNodes && node.childNodes.length > 0) {
      for (let i = 0; i < node.childNodes.length; i++) {
        const childNode = node.childNodes[i];
        if (childNode.expanded) {
          childNode.collapse();
          collapseAllChildren(childNode); // 递归调用关闭子节点的子节点
        }
      }
    }
  };
  // 展开和关闭其下所有子节点
  const expandNodes = (data: Object) => {
    let node = treeRef.value.getNode(data.resourceId);
    //展开选中的未展开的非叶子节点
    if (node.checked && !node.expanded && !node.isLeaf) {
      node.expand(() => {
        expandAllChildren(node);
      });
    }
    //关闭取下勾选的节点的所有子代节点
    if (!node.checked && node.expanded && !node.isLeaf) {
      collapseAllChildren(node);
      node.collapse();
    }
  };
  const checkChange = (data, selectNode,) => {
    const isCheck = treeRef.value.getCheckedNodes().indexOf(data) > -1
    expandNodes(data);
    checkNodes([data], isCheck);
  };
  const renderContent = (h, { node, data, store }: { node: Node, data: Tree, store: Node['store'] }) => {
    let checkbox = [];
    if (data.hasOwnProperty('buttonResourceList') && data.buttonResourceList.length) {
      data.buttonResourceList.forEach(item => {

        // 判断展开时的选中状态
        if (data.checked == true) {
          if (item.allSelect || !item.hasOwnProperty('allSelect')) {
            item.checked = true
            item.allSelect = false
          }
        } else {
          item.checked = false
          item.allSelect = true
        }
        checkbox.push(h(ElCheckbox, {
          props: {
            checked: item.checked
          },
          modelValue: item.checked,
          'onUpdate:modelValue': (value: any) => {
            item.checked = value;
          },
        }, { default: () => item.resourceName }))
      })
    }
    ;

    return h(
      'span',
      {
        class: 'custom-tree-node',
      },
      h('div', null, node.label),
      data.checked ? h(
        'span',
        {
          class: 'custom-checkbox'
        },
        checkbox,
      ) : '',
    );


  };
  // 获取所有选中的节点
  const getCheckedNodes = (flag = false) => {
    let arr = [];
    let nodes = treeRef.value.getCheckedNodes();
    nodes.forEach((val) => {
      arr.push(val.resourceId);
      if (val.hasOwnProperty('buttonResourceList')) {
        val.buttonResourceList.forEach((v) => {
          if (v.checked) arr.push(v.resourceId);
        });
      }
    });

    return flag ? [...arr, ...treeRef.value.getHalfCheckedKeys()] : arr;
  };
  // 获取已选中的节点和按钮
  const getTreeData = () => {
    readNodes(menuList.value);

  };
  // 清空选中树
  const clearTree = () => {
    treeRef.value.setCheckedKeys([]);

    // 清空选中的按钮权限
    clearNodes(menuList.value);


  };
  // 获取权限列表接口
  const getRsourceTreeApiFn = (tenantLevelId) => {
    return new Promise(reslove => {
      getRsourceTreeApi(tenantLevelId).then(res => {
        readNodes(res);
        menuList.value = res
        reslove(true)
      })
    })

  }

  onMounted(() => {
  });

  defineExpose({ getRsourceTreeApiFn, getCheckedNodes, getTreeData, });
</script>
<style lang="scss" scoped>
  ::v-deep .el-tree-node__content {
    height: auto !important;
    align-items: start
  }

  ::v-deep .custom-tree-node {
    flex: 1;
    display: flex;
    /* align-items: center; */
    flex-direction: column;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;

    div {
      height: 26.53px;
      line-height: 28.53px;
    }
  }

  ::v-deep .el-tree-node__expand-icon {
    height: 26px;
  }

  .custom-checkbox {
    white-space: pre-wrap;
  }
</style>
<style scoped></style>